/*
 * @Author: your name
 * @Date: 2022-03-14 15:23:02
 * @LastEditTime: 2022-03-22 17:57:23
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \xy-web-xiaoxi\src\views\manufacture\template\scripts\fill.js
 */

import { PROTOCAL_SEGMENT_BEGIN, PROTOCAL_SEGMENT_END, PROTOCAL_SEGMENT_SEPARATOR, buildElementId, getElementById } from './base'

export const PROTOCAL_SEGMENT_FILL = '2'

const handleAttribute = function(data, id, readonly) {
  let attributes = '<input class="template-col"  type="' + data.type + '"'
  if (id) {
    attributes += ' id="' + buildElementId(id) + '"'
  }
  if (readonly) {
    attributes += ' readonly'
  }
  if (data.value) {
    attributes += ' value="' + data.value + '"'
  }
  attributes += ' class="record-template-input-text"'
  return attributes
}

export function toHtml(params, id, readonly) {
  const data = params || {}
  let html = handleAttribute(data, id, readonly)
  if (data.type === 'text') {
    html += ' />'
  } else if (data.type === 'number') {
    html += 'step="0.001" />'
  } else if (data.type === 'date') {
    html += ' />'
  } else if (data.type === 'datetime') {
    html += ' />'
  }
  return html
}

export function toTemplate(params) {
  const data = params || {}
  return PROTOCAL_SEGMENT_BEGIN + PROTOCAL_SEGMENT_FILL + PROTOCAL_SEGMENT_SEPARATOR + JSON.stringify(data) + PROTOCAL_SEGMENT_END
}

export function getFillData(id) {
  const element = getElementById(id)
  if (element) {
    return element.value
  }
  return null
}

export function parseFillToHtml(segment, segmentValue, id, readonly) {
  if (!segment) {
    return null
  }
  const data = parseFillToData(segment, segmentValue)
  if (data) {
    return toHtml(data, id, readonly)
  }
  return null
}

export function parseFillToData(segment, segmentValue) {
  if (!segment) {
    return null
  }
  if (segment.startsWith(PROTOCAL_SEGMENT_FILL)) {
    // console.log(segment, 'parseFillToHtml')
    const segmentString = segment.substring(PROTOCAL_SEGMENT_FILL.length + PROTOCAL_SEGMENT_SEPARATOR.length)
    const data = JSON.parse(segmentString)
    if (segmentValue) {
      data.value = segmentValue
    }
    return data
  }
  return null
}
